package cn.ddm.hrm.service.impl;

import cn.ddm.hrm.client.LoginUserClient;
import cn.ddm.hrm.domain.Employee;
import cn.ddm.hrm.domain.LoginUser;
import cn.ddm.hrm.domain.Tenant;
import cn.ddm.hrm.dto.TenantEnteringDto;
import cn.ddm.hrm.exception.ErrorCode;
import cn.ddm.hrm.exception.ValidUtils;
import cn.ddm.hrm.mapper.EmployeeMapper;
import cn.ddm.hrm.mapper.TenantMapper;
import cn.ddm.hrm.query.TenantQuery;
import cn.ddm.hrm.service.ITenantService;
import cn.ddm.hrm.util.AjaxResult;
import cn.ddm.hrm.util.PageList;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ldm
 * @since 2022-01-02
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginUserClient loginUserClient;

    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {
        //分页条件，查询出来总数
        Page<Tenant> page = new Page<>(query.getPage(),query.getRows());
        //跨表查询出来结构
        List<Tenant> data =  tenantMapper.loadPageList(page,query);
        return new PageList<>(page.getTotal(),data);
    }

    @Override
    @Transactional
    public void entering(TenantEnteringDto dto) {
        // 机构入驻
        // 空值校验 加上注解以及在controller的注解

        // 判断用户是否存在
        Tenant tenant = dto.getTenant();
        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>().eq("company_name", tenant.getCompanyName()));
        /*if (tenants != null && tenants.size() > 0) {
            throw  new RuntimeException("租户已经入驻！直接登录");
        }*/
        ValidUtils.assertListNull(tenants, ErrorCode.CODE_403_SYSTEM_ERROR);
        // 查询管理员
        Employee employee = dto.getEmployee();
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>()
                .eq("username", employee.getUsername())
                .or()
                .eq("email", employee.getEmail())
                .or()
                .eq("tel", employee.getTel())
        );
        /*if (employees != null && employees.size() >0) {
            throw  new RuntimeException("您已经入驻过店铺了！登录后可以添加新的店铺！");
        }*/
        ValidUtils.assertListNull(employees, ErrorCode.CODE_500_SYSTEM_ERROR);
        // 保存数据
        // 先保存授权登录信息中保存用户
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(employee.getUsername());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String enPass = bCryptPasswordEncoder.encode(employee.getPassword());
        loginUser.setPassword(enPass);
        loginUser.setType(0);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        // 判断是否出现了问题
        if (!ajaxResult.isSuccess())
            throw  new RuntimeException(ajaxResult.getMessage());
        // 保存管理员
        employee.setLoginId(Long.valueOf( ajaxResult.getResultObj().toString()));
        employeeMapper.insert(employee);

        // 保存租户
        tenant.setAdminId(employee.getId());
        tenantMapper.insert(tenant);

        // 租户和套餐的中间表
        HashMap<String, Object> map = new HashMap<>();
        map.put("tenantId", tenant.getId());
        map.put("mealId", dto.getMealId());
        tenantMapper.saveTenatMeals(map);

    }
}
